<?php
/**
* Controller for managing the bindings between models via UIs.
*
* @package Scribble
*/
use Buan\Config;
use Buan\ModelCriteria;
use Buan\ModelManager;
class ModelBindingController extends ScribbleAdminController {

	/**
	* This method is used in conjunction with the "model-binding" core UI widget.
	* It displays all instances of a specified target model type, allows the user
	* to seelct one or more of these instances and then sends the selections back
	* to a specified callback function.
	*
	* It accepts the following GET parameters:
	* string callback			= The javascript function that handles the results
	* string targetmodel	= Target model type
	* int pn							= (optional) Pager no. to display
	* int smax						= (optional) Max. no. selections allowed
	* @return ScribbleAdminView
	*/
	public function browserWidget() {

		// Prepare views
		$view = new ScribbleAdminView();
		$view->popup();
		if(!$this->init($view)) {
			return $view;
		}
		$view->setSource(Config::get('ext.Scribble.dir.views').'/scribble/model-binding/browser-widget.tpl.php');

		// Gather widget config options
		$config = new StdClass();
		$config->targetmodel = isset($_GET['targetmodel']) ? $_GET['targetmodel'] : NULL;
		$config->callback = isset($_GET['callback']) ? $_GET['callback'] : '';
		$config->data = isset($_GET['data']) ? $_GET['data'] : '';
		$config->pn = isset($_GET['pn']) && $_GET['pn']>0 ? $_GET['pn'] : 1;
		$view->config = $config;

		// Handle AJAX calls
		if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest') {
			$this->browserWidgetAjax($config);
			exit();
		}

		// Result
		return $view;
	}

	/**
	* Handles various AJAX calls relating to the browser widget.
	*
	* @param StdClass Widget config
	* @return void
	*/
	private function browserWidgetAjax($config) {

		// Method: Load models
		if(isset($_POST['method']) && $_POST['method']=='load') {

			// Prepare result
			$feed = (object)array(
				'assets'=>array(),
				'pager'=>NULL,
				'errorCode'=>0,
				'errorMessage'=>''
			);

			// Prepare a pager
			$pager = (object)array(
				'size'=>25
			);

			// Build a criteria for loading models
			$c = new ModelCriteria();
			$c->setRange(($config->pn-1)*$pager->size, $config->pn*$pager->size);
			$feed->assets = ModelManager::select($config->targetmodel, $c)->asArray();
			foreach($feed->assets as $k=>$v) {
				$feed->assets[$k] = $v->idMeta();
			}

			// Response
			echo json_encode($feed);
			exit(0);
		}
	}
}
?>